﻿(function ($) {
    'use strict';

    $.jqPaginator = function (el, options) {
        if (!(this instanceof $.jqPaginator)) {
            return new $.jqPaginator(el, options);
        }

        var self = this;

        self.$container = $(el);

        self.$container.data('jqPaginator', self);

        self.init = function () {

            if (options.first || options.prev || options.next || options.last || options.page) {
                options = $.extend({}, {
                    first: '',
                    prev: '',
                    next: '',
                    last: '',
                    page: ''
                }, options);
            }

            self.options = $.extend({}, $.jqPaginator.defaultOptions, options);

            self.verify();

            self.extendJquery();

            self.render();

            self.fireEvent(this.options.currentPage, 'init');
        };

        self.verify = function () {
            var opts = self.options;

            if (!self.isNumber(opts.totalPages)) {
                throw new Error('[jqPaginator] type error: totalPages');
            }

            if (!self.isNumber(opts.totalCounts)) {
                throw new Error('[jqPaginator] type error: totalCounts');
            }

            if (!self.isNumber(opts.pageSize)) {
                throw new Error('[jqPaginator] type error: pageSize');
            }

            if (!self.isNumber(opts.currentPage)) {
                throw new Error('[jqPaginator] type error: currentPage');
            }

            if (!self.isNumber(opts.visiblePages)) {
                throw new Error('[jqPaginator] type error: visiblePages');
            }

            if (!opts.totalPages && !opts.totalCounts) {
                throw new Error('[jqPaginator] totalCounts or totalPages is required');
            }

            if (!opts.totalPages && !opts.totalCounts) {
                throw new Error('[jqPaginator] totalCounts or totalPages is required');
            }

            if (!opts.totalPages && opts.totalCounts && !opts.pageSize) {
                throw new Error('[jqPaginator] pageSize is required');
            }

            if (opts.totalCounts && opts.pageSize) {
                opts.totalPages = Math.ceil(opts.totalCounts / opts.pageSize);
            }

            if (opts.currentPage < 1 || opts.currentPage > opts.totalPages) {
                throw new Error('[jqPaginator] currentPage is incorrect');
            }

            if (opts.totalPages < 1) {
                throw new Error('[jqPaginator] totalPages cannot be less currentPage');
            }
        };

        self.extendJquery = function () {
            $.fn.jqPaginatorHTML = function (s) {
                return s ? this.before(s).remove() : $('<p>').append(this.eq(0).clone()).html();
            };
        };

        self.render = function () {
            self.renderHtml();
            self.setStatus();
            self.bindEvents();
        };

        self.renderHtml = function () {
            var html = [];

            var pages = self.getPages();
            for (var i = 0, j = pages.length; i < j; i++) {
                html.push(self.buildItem('page', pages[i]));
            }

            self.isEnable('prev') && html.unshift(self.buildItem('prev', self.options.currentPage - 1));
            self.isEnable('first') && html.unshift(self.buildItem('first', 1));
            self.isEnable('statistics') && html.unshift(self.buildItem('statistics'));
            self.isEnable('next') && html.push(self.buildItem('next', self.options.currentPage + 1));
            self.isEnable('last') && html.push(self.buildItem('last', self.options.totalPages));

            if (self.options.wrapper) {
                self.$container.html($(self.options.wrapper).html(html.join('')).jqPaginatorHTML());
            } else {
                self.$container.html(html.join(''));
            }
        };

        self.buildItem = function (type, pageData) {
            var html = self.options[type]
                .replace(/{{page}}/g, pageData)
                .replace(/{{totalPages}}/g, self.options.totalPages)
                .replace(/{{totalCounts}}/g, self.options.totalCounts);

            return $(html).attr({
                'jp-role': type,
                'jp-data': pageData
            }).jqPaginatorHTML();
        };

        self.setStatus = function () {
            var options = self.options;

            if (!self.isEnable('first') || options.currentPage === 1) {
                $('[jp-role=first]', self.$container).addClass(options.disableClass);
            }
            if (!self.isEnable('prev') || options.currentPage === 1) {
                $('[jp-role=prev]', self.$container).addClass(options.disableClass);
            }
            if (!self.isEnable('next') || options.currentPage >= options.totalPages) {
                $('[jp-role=next]', self.$container).addClass(options.disableClass);
            }
            if (!self.isEnable('last') || options.currentPage >= options.totalPages) {
                $('[jp-role=last]', self.$container).addClass(options.disableClass);
            }

            $('[jp-role=page]', self.$container).removeClass(options.activeClass);
            $('[jp-role=page][jp-data=' + options.currentPage + ']', self.$container).addClass(options.activeClass);
        };

        self.getPages = function () {
            var pages = [],
                visiblePages = self.options.visiblePages,
                currentPage = self.options.currentPage,
                totalPages = self.options.totalPages;

            if (visiblePages > totalPages) {
                visiblePages = totalPages;
            }

            var half = Math.floor(visiblePages / 2);
            var start = currentPage - half + 1 - visiblePages % 2;
            var end = currentPage + half;

            if (start < 1) {
                start = 1;
                end = visiblePages;
            }
            if (end > totalPages) {
                end = totalPages;
                start = 1 + totalPages - visiblePages;
            }

            var itPage = start;
            while (itPage <= end) {
                pages.push(itPage);
                itPage++;
            }

            return pages;
        };

        self.isNumber = function (value) {
            var type = typeof value;
            return type === 'number' || type === 'undefined';
        };

        self.isEnable = function (type) {
            return self.options[type] && typeof self.options[type] === 'string';
        };

        self.switchPage = function (pageIndex) {
            self.options.currentPage = pageIndex;
            self.render();
        };

        self.fireEvent = function (pageIndex, type) {
            return (typeof self.options.onPageChange !== 'function') || (self.options.onPageChange(pageIndex, type) !== false);
        };

        self.callMethod = function (method, options) {
            switch (method) {
                case 'option':
                    self.options = $.extend({}, self.options, options);
                    self.verify();
                    self.render();
                    break;
                case 'destroy':
                    self.$container.empty();
                    self.$container.removeData('jqPaginator');
                    break;
                default:
                    throw new Error('[jqPaginator] method "' + method + '" does not exist');
            }

            return self.$container;
        };

        self.bindEvents = function () {
            var opts = self.options;

            self.$container.off();
            self.$container.on('click', '[jp-role]', function () {
                var $el = $(this);
                if ($el.hasClass(opts.disableClass) || $el.hasClass(opts.activeClass)) {
                    return;
                }

                var pageIndex = +$el.attr('jp-data');
                if (self.fireEvent(pageIndex, 'change')) {
                    self.switchPage(pageIndex);
                }
            });
        };

        self.init();

        return self.$container;
    };

    $.jqPaginator.defaultOptions = {
        wrapper: '',
        first: '<li class="first"><a href="javascript:;">首页</a></li>',
        prev: '<li class="prev"><a href="javascript:;">上一页</a></li>',
        next: '<li class="next"><a href="javascript:;">下一页</a></li>',
        last: '<li class="last"><a href="javascript:;">末页</a></li>',
        page: '<li class="page"><a href="javascript:;">{{page}}</a></li>',
        totalPages: 0,
        totalCounts: 0,
        pageSize: 10,
        currentPage: 1,
        visiblePages: 7,
        disableClass: 'disabled',
        activeClass: 'active',
        onPageChange: null
    };

    $.fn.jqPaginator = function () {
        var self = this,
            args = Array.prototype.slice.call(arguments);

        if (typeof args[0] === 'string') {
            var $instance = $(self).data('jqPaginator');
            if (!$instance) {
                throw new Error('[jqPaginator] the element is not instantiated');
            } else {
                return $instance.callMethod(args[0], args[1]);
            }
        } else {
            return new $.jqPaginator(this, args[0]);
        }
    };

})(jQuery);

var BindCloudGrid_HasNumberControl = false;
//RecordTotalNum 记录总数；currentPage 当前页码
function BindCloudGrid(el, RecordTotalNum, PageIndex) {
    el.attr("cellspacing", "0");
    var PageSize = 10;//每页记录数
    if (el.attr("PageSize")) {
        PageSize = el.attr("PageSize");
    } else {
        var wheight = $(window).height();
        if (wheight >= 1000) {
            PageSize = 20;
        } else if (wheight >= 800) {
            PageSize = 15;
        }
    }

    var vPages = 10;//显示多少页
    if (el.attr("visiblePages")) {
        vPages = parseInt(el.attr("visiblePages"));
    }

    var URL = el.attr('url');//读取数据地址
    var parm = el.attr('OtherParm');//其他需要传递的参数
    var RelationPageID = el.attr('RelationPageID');//分页控件显示的ID

    if (parm && parm != '') {
        AjaxData = eval(parm)();
    }
    if (RelationPageID) {//绑定了分页控件 并且传递了当前页码
        if (PageIndex)
            $(AjaxData).attr('PageIndex', PageIndex);
        else {
            var jpdata = $('#' + RelationPageID).attr('PageIndex');
            if (jpdata) {
                PageIndex = parseInt(jpdata);//上次选中的页码
                $(AjaxData).attr('PageIndex', PageIndex);
            } else {
                $(AjaxData).attr('PageIndex', 1);
            }
        }

        $(AjaxData).attr('PageSize', PageSize);
    }
    PageIndex = PageIndex ? PageIndex : 1;
    //绑定Grid数据
    CloudPost(AjaxData, URL,
        function (response) {
            el.find(".RowStyle").remove();
            var HeadSet = el.find(".HeaderStyle > th");
            BindCloudGrid_HasNumberControl = false;
            //加载td
            $(response.data.rows).each(function (index) {
                XDGridRowHTML(el, this, index, HeadSet, true, (PageIndex - 1) * PageSize);
            });

            //操作事件
            el.find(".gridOp").click(function () {
                var RowData = response.data.rows[$(this).parent().parent().attr('mIndex')];
                eval($(this).attr('FunctionName'))(RowData, $(this));
            });


            //固定list页面底部按钮区
            if ($.isFunction(window.FixBottomBtn))
                FixBottomBtn();

            if (BindCloudGrid_HasNumberControl) {//存在数字控件 需要初始化参数
                ControlNumber();
            }

            //绑定成功后执行事件
            var AfterBindFun = el.attr('AfterBind');
            if (AfterBindFun && AfterBindFun != '') {
                eval(AfterBindFun)(response.data.rows);
            }

            if (RelationPageID && (!RecordTotalNum || response.data.total != RecordTotalNum)) {//绑定了分页控件 &&(页面初始化时||记录总数发生改变)
                var totalP = response.total / PageSize;
                if (totalP != parseInt(response.data.total / PageSize)) {//非整数
                    totalP = parseInt(response.data.total / PageSize) + 1;
                } else if (totalP == 0)
                    totalP = 1;

                if (PageIndex && PageIndex > totalP) {//超出总页数 重新加载数据，定位到最后一页
                    $('#' + RelationPageID).attr('PageIndex', totalP);
                    BindCloudGrid(el);
                }
                else {
                    //绑定分页控件
                    $.jqPaginator('#' + RelationPageID, {
                        totalPages: totalP,
                        visiblePages: vPages,
                        currentPage: PageIndex,
                        onPageChange: function (num, type) {
                            $('#' + RelationPageID).attr('PageIndex', num);
                            if (type == 'change') {//点击分页时执行，其他情况下TotalPageNum=undefined
                                BindCloudGrid(el, response.data.total, num);
                            }
                        }
                    });
                }
            }
        });
};

function XDGridAddTr(el, RowData, content) {
    var HeadSet = el.find(".HeaderStyle > th");
    var TR = XDGridRowHTML(el, RowData, -9999, HeadSet, false, 0);
    content.after(TR);

    //固定list页面底部按钮区
    if ($.isFunction(window.FixBottomBtn))
        FixBottomBtn();

    //存在数字控件 需要初始化参数
    if (BindCloudGrid_HasNumberControl) {
        ControlNumber();
    }
    return TR;
}

function XDGridRowHTML(el, RowData, index, HeadSet, AutoAppend, XuHao) {
    var KeyID = RowData[el.attr('KeyID')];

    var tr = $("<tr class='RowStyle' mIndex='" + index + "' KeyID='" + (KeyID ? KeyID : '') + "'></tr>");
    if (AutoAppend)
        tr.appendTo(el);
    var TRValue = '';
    HeadSet.each(function () {
        var FieldID = $(this).attr('Field');
        var align = '';
        if ($(this).attr('RowAlign')) {
            align = " align='" + $(this).attr('RowAlign') + "'";
        }
        else
            align = '';

        switch (FieldID) {
            case "check"://选择列
                if ($(this).html().replace(/ |\s/g, '') == '') {
                    $("<input type='checkbox'/>").appendTo($(this)).change(function () {//全选
                        el.find("input[id^='chk_SelectColumn_']").prop("checked", $(this).prop("checked"));
                    });
                }
                align = " align='center'";
                TRValue = '<input id="chk_SelectColumn_' + index + '" type="checkbox"/>';
                break;
            case "index"://序号
                TRValue = index + 1 + XuHao;
                break;
            case "ViewButton"://操作按钮
                TRValue = "<span class=\"ui-icon-small ui-icon-small-view gridOp\" FunctionName=\"" + $(this).attr('FunctionName') + "\"></span>";
                break;
            case "EditButton"://修改
                TRValue = "<span class=\"ui-icon-small ui-icon-small-edit gridOp\" FunctionName=\"" + $(this).attr('FunctionName') + "\"></span>";
                break;
            case "DelButton"://删除
                TRValue = "<span class=\"ui-icon-small ui-icon-small-delete gridOp\" FunctionName=\"DelXDGridDataOne\"></span>";
                break;
            case "function"://通过方法获取值
                if ($(this).attr('FunctionName')) {
                    TRValue = eval($(this).attr('FunctionName'))(RowData, tr);
                }
                break;
            default:
                TRValue = RowData[FieldID];
                if (!TRValue)
                    TRValue = '';

                if ($(this).attr('CodeName')) {
                    TRValue = CNameManage_IText($(this).attr('CodeName'), TRValue, index);
                }
                break;
        }

        var ControlType = $(this).attr('ControlType');
        if (ControlType) {
            if (ControlType.toLowerCase() != "text" && ControlType.toLowerCase() != "date")
                BindCloudGrid_HasNumberControl = true;
            TRValue = jsGetControl(ControlType, $(this), TRValue, KeyID);
        }
        $("<td" + align + " Field='" + FieldID + "'>" + TRValue + "</td>").appendTo(tr);
    });
    return tr;
}
function CloudGridChecked(el) {
    var SelV = el.find("input[id^='chk_SelectColumn_']:checked");
    if (SelV.length == 0) {
        OpenAlert('未选择记录！');
        return "";
    }
    var Values = "";
    SelV.each(function () {
        Values += $(this).parent().parent().attr('KeyID') + ";"
    });
    return Values;
}
function DelXDGridDataOne(DataRow, JQ_TD_Span/*按钮实例*/) {
    zConfirm('是否确定删除？', 'XDGridDataAfterDel("' + JQ_TD_Span.parents('table').eq(0).attr('id') + '","' + JQ_TD_Span.parents('tr').eq(0).attr('KeyID') + '")');
}
//删除数据
function DelXDGridData(el, Datas) {
    zConfirm('是否确定删除？', 'XDGridDataAfterDel("' + el.attr('id') + '","' + CloudGridChecked(el) + '")');
}

//删除记录
function XDGridDataAfterDel(GridID, Values) {
    el = $("#" + GridID);
    //调用的方法名称
    JsonAjax({ 'Method': el.attr('delmethod'), 'KeyID': Values }, el.attr('url'),
        function (result) {

            BindCloudGrid(el);
        });
}

var CNameJSON = { '代码名称': '代码值JSON串' };
//根据代码值获取名称
function CNameManage_IText(CName, IValue, index) {
    var ValueJS = CNameJSON[CName];
    if (ValueJS) {//存在 直接通过值取名称
        if (IValue == '')
            return '';
        IValue = ValueJS[IValue];
        if (IValue) {
            return IValue;
        } else
            return '';
    } else {//读取
        //alert(index);
        if (index == 0)//第一次需要初始化记录
            CNameManage_Data(CName);
        if (IValue == '')
            return '';
        return '<span class="' + CName + '" Values="' + IValue + '"></span>';
    }
}

function CNameManage_Data(CName) {
    JsonAjax({ 'CodeName': CName, 'ParentIValue': '' }, getRootPath() + "/XD.DataManage/ItemData.ashx",
        function (response) {
            var DV = '{';
            $(response.data.rows).each(function () {
                DV += '"' + this.IValue + '":"' + this.IName + '",';
            });
            DV += '"END":"END"}';
            $(CNameJSON).attr(CName, $.parseJSON(DV));
            //alert(CNameJSON[CName]);
            $("." + CName).each(function () {
                $(this).html(CNameManage_IText(CName, $(this).attr('Values')));
            });
        });
}

//绑定控件
function jsGetControl(ControlType, el, TRValue, KeyValue) {
    var ID = el.attr('Field') + '_' + KeyValue;//字段名称+唯一编码
    var required = el.attr('Required');
    var ConStyle = el.attr('ConStyle');
    if (!required) {//非必填情况下 控件宽度98%
        if (!ConStyle || ConStyle == '') {
            ConStyle = "width:98%";
        }
    }
    switch (ControlType.toLowerCase()) {
        case "text":
            return jsTextBox(ID, TRValue, required, ConStyle, el.attr('MaxLength'), el.attr('MinLength'));
            break;
        case "numeric":
            return jsInputNumeric(ID, TRValue, el.attr('DecimalPlaces'), required, ConStyle, el.attr('MaxValue'), el.attr('MinValue'));
            break;
        case "money":
            return jsInputMoney(ID, TRValue, el.attr('DecimalPlaces'), required, ConStyle, el.attr('MaxValue'), el.attr('MinValue'));
            break;
        case "date":
            return jsDatePicker(ID, TRValue, required, ConStyle);
            break;
        default:
            return TRValue;
            break;
    }
}

function jsTextBox(id, value, required, style, maxlength, minlength) {
    return '<input name="' + id + '" type="text" value="' + value + '" id="' + id + '" class="TextBoxStyle" ' + (style && style != '' ? 'style="' + style + '"' : '') +
        (required ? ' required=true' : '') +
        (maxlength ? ' maxlength="' + maxlength + '"' : '') +
        (minlength ? ' minlength="' + minlength + '" data-msg-minlength="请至少输入' + minlength + '位" ' : '') +
        ' />';

}

function jsInputNumeric(id, value, DecimalPlaces, required, style, MaxValue, MinValue) {
    return '<input name="' + id + '" type="text" value="' + value + '" id="' + id + '" class="TextBoxStyle" XDtype="number" XDReg="数字|' +
        (DecimalPlaces ? DecimalPlaces : 0) + '|' +
        (MaxValue ? MaxValue : '') + '|' +
        (MinValue ? MinValue : '') + '" ' +
        (required ? ' required=true' : '') +
        (style && style != '' ? ' style="' + style + '"' : '') + ' />';
}

function jsInputMoney(id, value, DecimalPlaces, required, style, MaxValue, MinValue) {
    if (!DecimalPlaces)
        DecimalPlaces = 0;
    value = ConvertMoney(value, DecimalPlaces);

    return '<input name="' + id + '" type="text" value="' + value + '" id="' + id + '" class="TextBoxStyle" XDtype="number" XDReg="数字|' +
        DecimalPlaces + '|' +
        (MaxValue ? MaxValue : '') + '|' +
        (MinValue ? MinValue : '') + '|1" ' +
        (required ? ' required=true' : '') +
        ' style="' + (style ? style : '') + ';text-align:right" />';
}

function jsDatePicker(id, value, required, style) {
    return '<input name="' + id + '" type="text" value="' + value + '" id="' + id + '" class="TextBoxStyle"  ' +
        ' onfocus="WdatePicker({dateFmt:\'yyyy-MM-dd\'})" ' +
        (required ? ' required=true' : '') +
        (style && style != '' ? ' style="' + style + '"' : '') + ' />';
}